<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="language" content="en" />
        <link href="./assets/ffd55088/css/bootstrap.css" rel="stylesheet">
<link href="./assets/5cf9384a/solarized_light.css" rel="stylesheet">
<link href="./assets/6c54116e/style.css" rel="stylesheet">
<script src="./assets/a44cef0f/jquery.js"></script>
<script src="./assets/ffd55088/js/bootstrap.js"></script>
<script src="./assets/8ac4e28a/jssearch.js"></script>    <title>Data Widgets - Displaying Data - The Definitive Guide to Yii 2.0</title>
</head>
<body>

<div class="wrap">
    <nav id="w1460" class="navbar-inverse navbar-fixed-top navbar" role="navigation"><div class="navbar-header"><button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#w1460-collapse"><span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span></button><a class="navbar-brand" href="./index.html">The Definitive Guide to Yii 2.0</a></div><div id="w1460-collapse" class="collapse navbar-collapse"><ul id="w1461" class="navbar-nav nav"><li><a href="./index.html">Class reference</a></li>
<li class="dropdown"><a class="dropdown-toggle" href="#" data-toggle="dropdown">Extensions <b class="caret"></b></a><ul id="w1462" class="dropdown-menu"><li><a href="./ext-apidoc-index.html" tabindex="-1">apidoc</a></li>
<li><a href="./ext-authclient-index.html" tabindex="-1">authclient</a></li>
<li><a href="./ext-bootstrap-index.html" tabindex="-1">bootstrap</a></li>
<li><a href="./ext-codeception-index.html" tabindex="-1">codeception</a></li>
<li><a href="./ext-debug-index.html" tabindex="-1">debug</a></li>
<li><a href="./ext-elasticsearch-index.html" tabindex="-1">elasticsearch</a></li>
<li><a href="./ext-faker-index.html" tabindex="-1">faker</a></li>
<li><a href="./ext-gii-index.html" tabindex="-1">gii</a></li>
<li><a href="./ext-imagine-index.html" tabindex="-1">imagine</a></li>
<li><a href="./ext-jui-index.html" tabindex="-1">jui</a></li>
<li><a href="./ext-mongodb-index.html" tabindex="-1">mongodb</a></li>
<li><a href="./ext-redis-index.html" tabindex="-1">redis</a></li>
<li><a href="./ext-smarty-index.html" tabindex="-1">smarty</a></li>
<li><a href="./ext-sphinx-index.html" tabindex="-1">sphinx</a></li>
<li><a href="./ext-swiftmailer-index.html" tabindex="-1">swiftmailer</a></li>
<li><a href="./ext-twig-index.html" tabindex="-1">twig</a></li></ul></li>
<li><a href="./guide-README.html">Guide</a></li></ul><div class="navbar-form navbar-left" role="search">
  <div class="form-group">
    <input id="searchbox" type="text" class="form-control" placeholder="Search">
  </div>
</div>
</div></nav>
    <div id="search-resultbox" style="display: none;" class="modal-content">
        <ul id="search-results">
        </ul>
    </div>

    
<div class="row">
    <div class="col-md-2">
                <div id="navigation" class="list-group"><a class="list-group-item" href="#navigation-1444" data-toggle="collapse" data-parent="#navigation">Introduction <b class="caret"></b></a><div id="navigation-1444" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-intro-yii.html">About Yii</a>
<a class="list-group-item" href="./guide-intro-upgrade-from-v1.html">Upgrading from Version 1.1</a></div>
<a class="list-group-item" href="#navigation-1445" data-toggle="collapse" data-parent="#navigation">Getting Started <b class="caret"></b></a><div id="navigation-1445" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-start-installation.html">Installing Yii</a>
<a class="list-group-item" href="./guide-start-workflow.html">Running Applications</a>
<a class="list-group-item" href="./guide-start-hello.html">Saying Hello</a>
<a class="list-group-item" href="./guide-start-forms.html">Working with Forms</a>
<a class="list-group-item" href="./guide-start-databases.html">Working with Databases</a>
<a class="list-group-item" href="./guide-start-gii.html">Generating Code with Gii</a>
<a class="list-group-item" href="./guide-start-looking-ahead.html">Looking Ahead</a></div>
<a class="list-group-item" href="#navigation-1446" data-toggle="collapse" data-parent="#navigation">Application Structure <b class="caret"></b></a><div id="navigation-1446" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-structure-overview.html">Overview</a>
<a class="list-group-item" href="./guide-structure-entry-scripts.html">Entry Scripts</a>
<a class="list-group-item" href="./guide-structure-applications.html">Applications</a>
<a class="list-group-item" href="./guide-structure-application-components.html">Application Components</a>
<a class="list-group-item" href="./guide-structure-controllers.html">Controllers</a>
<a class="list-group-item" href="./guide-structure-models.html">Models</a>
<a class="list-group-item" href="./guide-structure-views.html">Views</a>
<a class="list-group-item" href="./guide-structure-modules.html">Modules</a>
<a class="list-group-item" href="./guide-structure-filters.html">Filters</a>
<a class="list-group-item" href="./guide-structure-widgets.html">Widgets</a>
<a class="list-group-item" href="./guide-structure-assets.html">Assets</a>
<a class="list-group-item" href="./guide-structure-extensions.html">Extensions</a></div>
<a class="list-group-item" href="#navigation-1447" data-toggle="collapse" data-parent="#navigation">Handling Requests <b class="caret"></b></a><div id="navigation-1447" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-runtime-overview.html">Overview</a>
<a class="list-group-item" href="./guide-runtime-bootstrapping.html">Bootstrapping</a>
<a class="list-group-item" href="./guide-runtime-routing.html">Routing and URL Creation</a>
<a class="list-group-item" href="./guide-runtime-requests.html">Requests</a>
<a class="list-group-item" href="./guide-runtime-responses.html">Responses</a>
<a class="list-group-item" href="./guide-runtime-sessions-cookies.html">Sessions and Cookies</a>
<a class="list-group-item" href="./guide-runtime-handling-errors.html">Handling Errors</a>
<a class="list-group-item" href="./guide-runtime-logging.html">Logging</a></div>
<a class="list-group-item" href="#navigation-1448" data-toggle="collapse" data-parent="#navigation">Key Concepts <b class="caret"></b></a><div id="navigation-1448" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-concept-components.html">Components</a>
<a class="list-group-item" href="./guide-concept-properties.html">Properties</a>
<a class="list-group-item" href="./guide-concept-events.html">Events</a>
<a class="list-group-item" href="./guide-concept-behaviors.html">Behaviors</a>
<a class="list-group-item" href="./guide-concept-configurations.html">Configurations</a>
<a class="list-group-item" href="./guide-concept-aliases.html">Aliases</a>
<a class="list-group-item" href="./guide-concept-autoloading.html">Class Autoloading</a>
<a class="list-group-item" href="./guide-concept-service-locator.html">Service Locator</a>
<a class="list-group-item" href="./guide-concept-di-container.html">Dependency Injection Container</a></div>
<a class="list-group-item" href="#navigation-1449" data-toggle="collapse" data-parent="#navigation">Working with Databases <b class="caret"></b></a><div id="navigation-1449" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-db-dao.html">Data Access Objects</a>
<a class="list-group-item" href="./guide-db-query-builder.html">Query Builder</a>
<a class="list-group-item" href="./guide-db-active-record.html">Active Record</a>
<a class="list-group-item" href="./guide-db-migrations.html">Migrations</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-sphinx/blob/master/docs/guide/README.md">Sphinx</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-redis/blob/master/docs/guide/README.md">Redis</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-mongodb/blob/master/docs/guide/README.md">MongoDB</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/README.md">ElasticSearch</a></div>
<a class="list-group-item" href="#navigation-1450" data-toggle="collapse" data-parent="#navigation">Getting Data from Users <b class="caret"></b></a><div id="navigation-1450" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-input-forms.html">Creating Forms</a>
<a class="list-group-item" href="./guide-input-validation.html">Validating Input</a>
<a class="list-group-item" href="./guide-input-file-upload.html">Uploading Files</a>
<a class="list-group-item" href="./guide-input-tabular-input.html">Collecting Tabular Input</a>
<a class="list-group-item" href="./guide-input-multiple-models.html">Getting Data for Multiple Models</a></div>
<a class="list-group-item active" href="#navigation-1451" data-toggle="collapse" data-parent="#navigation">Displaying Data <b class="caret"></b></a><div id="navigation-1451" class="submenu panel-collapse collapse in"><a class="list-group-item" href="./guide-output-formatting.html">Data Formatting</a>
<a class="list-group-item" href="./guide-output-pagination.html">Pagination</a>
<a class="list-group-item" href="./guide-output-sorting.html">Sorting</a>
<a class="list-group-item" href="./guide-output-data-providers.html">Data Providers</a>
<a class="list-group-item active" href="./guide-output-data-widgets.html">Data Widgets</a>
<a class="list-group-item" href="./guide-output-client-scripts.html">Working with Client Scripts</a>
<a class="list-group-item" href="./guide-output-theming.html">Theming</a></div>
<a class="list-group-item" href="#navigation-1452" data-toggle="collapse" data-parent="#navigation">Security <b class="caret"></b></a><div id="navigation-1452" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-security-overview.html">Overview</a>
<a class="list-group-item" href="./guide-security-authentication.html">Authentication</a>
<a class="list-group-item" href="./guide-security-authorization.html">Authorization</a>
<a class="list-group-item" href="./guide-security-passwords.html">Working with Passwords</a>
<a class="list-group-item" href="./guide-security-cryptography.html">Cryptography</a>
<a class="list-group-item" href="./guide-structure-views.html#security">Views security</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-authclient/blob/master/docs/guide/README.md">Auth Clients</a>
<a class="list-group-item" href="./guide-security-best-practices.html">Best Practices</a></div>
<a class="list-group-item" href="#navigation-1453" data-toggle="collapse" data-parent="#navigation">Caching <b class="caret"></b></a><div id="navigation-1453" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-caching-overview.html">Overview</a>
<a class="list-group-item" href="./guide-caching-data.html">Data Caching</a>
<a class="list-group-item" href="./guide-caching-fragment.html">Fragment Caching</a>
<a class="list-group-item" href="./guide-caching-page.html">Page Caching</a>
<a class="list-group-item" href="./guide-caching-http.html">HTTP Caching</a></div>
<a class="list-group-item" href="#navigation-1454" data-toggle="collapse" data-parent="#navigation">RESTful Web Services <b class="caret"></b></a><div id="navigation-1454" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-rest-quick-start.html">Quick Start</a>
<a class="list-group-item" href="./guide-rest-resources.html">Resources</a>
<a class="list-group-item" href="./guide-rest-controllers.html">Controllers</a>
<a class="list-group-item" href="./guide-rest-routing.html">Routing</a>
<a class="list-group-item" href="./guide-rest-response-formatting.html">Response Formatting</a>
<a class="list-group-item" href="./guide-rest-authentication.html">Authentication</a>
<a class="list-group-item" href="./guide-rest-rate-limiting.html">Rate Limiting</a>
<a class="list-group-item" href="./guide-rest-versioning.html">Versioning</a>
<a class="list-group-item" href="./guide-rest-error-handling.html">Error Handling</a></div>
<a class="list-group-item" href="#navigation-1455" data-toggle="collapse" data-parent="#navigation">Development Tools <b class="caret"></b></a><div id="navigation-1455" class="submenu panel-collapse collapse"><a class="list-group-item" href="https://github.com/yiisoft/yii2-debug/blob/master/docs/guide/README.md">Debug Toolbar and Debugger</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-gii/blob/master/docs/guide/README.md">Generating Code using Gii</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-apidoc">Generating API Documentation</a></div>
<a class="list-group-item" href="#navigation-1456" data-toggle="collapse" data-parent="#navigation">Testing <b class="caret"></b></a><div id="navigation-1456" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-test-overview.html">Overview</a>
<a class="list-group-item" href="./guide-test-environment-setup.html">Testing environment setup</a>
<a class="list-group-item" href="./guide-test-unit.html">Unit Tests</a>
<a class="list-group-item" href="./guide-test-functional.html">Functional Tests</a>
<a class="list-group-item" href="./guide-test-acceptance.html">Acceptance Tests</a>
<a class="list-group-item" href="./guide-test-fixtures.html">Fixtures</a></div>
<a class="list-group-item" href="#navigation-1457" data-toggle="collapse" data-parent="#navigation">Special Topics <b class="caret"></b></a><div id="navigation-1457" class="submenu panel-collapse collapse"><a class="list-group-item" href="https://github.com/yiisoft/yii2-app-advanced/blob/master/docs/guide/README.md">Advanced Project Template</a>
<a class="list-group-item" href="./guide-tutorial-start-from-scratch.html">Building Application from Scratch</a>
<a class="list-group-item" href="./guide-tutorial-console.html">Console Commands</a>
<a class="list-group-item" href="./guide-tutorial-core-validators.html">Core Validators</a>
<a class="list-group-item" href="./guide-tutorial-i18n.html">Internationalization</a>
<a class="list-group-item" href="./guide-tutorial-mailing.html">Mailing</a>
<a class="list-group-item" href="./guide-tutorial-performance-tuning.html">Performance Tuning</a>
<a class="list-group-item" href="./guide-tutorial-shared-hosting.html">Shared Hosting Environment</a>
<a class="list-group-item" href="./guide-tutorial-template-engines.html">Template Engines</a>
<a class="list-group-item" href="./guide-tutorial-yii-integration.html">Working with Third-Party Code</a></div>
<a class="list-group-item" href="#navigation-1458" data-toggle="collapse" data-parent="#navigation">Widgets <b class="caret"></b></a><div id="navigation-1458" class="submenu panel-collapse collapse"><a class="list-group-item" href="https://github.com/yiisoft/yii2-bootstrap/blob/master/docs/guide/README.md">Bootstrap Widgets</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-jui/blob/master/docs/guide/README.md">jQuery UI Widgets</a></div>
<a class="list-group-item" href="#navigation-1459" data-toggle="collapse" data-parent="#navigation">Helpers <b class="caret"></b></a><div id="navigation-1459" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-helper-overview.html">Overview</a>
<a class="list-group-item" href="./guide-helper-array.html">ArrayHelper</a>
<a class="list-group-item" href="./guide-helper-html.html">Html</a>
<a class="list-group-item" href="./guide-helper-url.html">Url</a></div></div>    </div>
    <div class="col-md-9 guide-content" role="main">
        <h1>Data widgets <span id="data-widgets"></span><a href="#data-widgets" class="hashlink">&para;</a></h1>
<div class="toc"><ol><li><a href="#detailview">DetailView </a></li>
<li><a href="#listview">ListView </a></li>
<li><a href="#gridview">GridView </a></li>
<li><a href="#further-reading">Further reading</a></li></ol></div>
<p>Yii provides a set of <a href="guide-structure-widgets.html">widgets</a> that can be used to display data.
While the <a href="#detail-view">DetailView</a> widget can be used to display data for a single record,
<a href="#list-view">ListView</a> and <a href="#grid-view">GridView</a> can be used to display a list or table of data records
providing features like pagination, sorting and filtering.</p>
<h2>DetailView <a name="detail-view"></a> <span id="detailview"></span><a href="#detailview" class="hashlink">&para;</a></h2><p>The <a href="./yii-widgets-detailview.html">DetailView</a> widget displays the details of a single data <a href="./yii-widgets-detailview.html#$model-detail">model</a>.</p>
<p>It is best used for displaying a model in a regular format (e.g. each model attribute is displayed as a row in a table).
The model can be either an instance or subclass of <a href="./yii-base-model.html">yii\base\Model</a> such as an <a href="guide-db-active-record.html">active record</a> or an associative array.</p>
<p>DetailView uses the <a href="./yii-widgets-detailview.html#$attributes-detail">$attributes</a> property to determine which model attributes should be displayed and how they
should be formatted. See the <a href="guide-output-formatting.html">formatter section</a> for available formatting options.</p>
<p>A typical usage of DetailView is as follows:</p>
<pre><code class="hljs php language-php"><span class="hljs-keyword">echo</span> DetailView::widget([
    <span class="hljs-string">'model'</span> =&gt; <span class="hljs-variable">$model</span>,
    <span class="hljs-string">'attributes'</span> =&gt; [
        <span class="hljs-string">'title'</span>,               <span class="hljs-comment">// title attribute (in plain text)</span>
        <span class="hljs-string">'description:html'</span>,    <span class="hljs-comment">// description attribute formatted as HTML</span>
        [                      <span class="hljs-comment">// the owner name of the model</span>
            <span class="hljs-string">'label'</span> =&gt; <span class="hljs-string">'Owner'</span>,
            <span class="hljs-string">'value'</span> =&gt; <span class="hljs-variable">$model</span>-&gt;owner-&gt;name,
        ],
        <span class="hljs-string">'created_at:datetime'</span>, <span class="hljs-comment">// creation date formatted as datetime</span>
    ],
]);
</code></pre>
<h2>ListView <a name="list-view"></a> <span id="listview"></span><a href="#listview" class="hashlink">&para;</a></h2><p>The <a href="./yii-widgets-listview.html">ListView</a> widget is used to display data from a <a href="guide-output-data-providers.html">data provider</a>.
Each data model is rendered using the specified <a href="./yii-widgets-listview.html#$itemView-detail">view file</a>.
Since it provides features such as pagination, sorting and filtering out of the box, it is handy both to display
information to end user and to create data managing UI.</p>
<p>A typical usage is as follows:</p>
<pre><code class="hljs php language-php"><span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">widgets</span>\<span class="hljs-title">ListView</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">data</span>\<span class="hljs-title">ActiveDataProvider</span>;

<span class="hljs-variable">$dataProvider</span> = <span class="hljs-keyword">new</span> ActiveDataProvider([
    <span class="hljs-string">'query'</span> =&gt; Post::find(),
    <span class="hljs-string">'pagination'</span> =&gt; [
        <span class="hljs-string">'pageSize'</span> =&gt; <span class="hljs-number">20</span>,
    ],
]);
<span class="hljs-keyword">echo</span> ListView::widget([
    <span class="hljs-string">'dataProvider'</span> =&gt; <span class="hljs-variable">$dataProvider</span>,
    <span class="hljs-string">'itemView'</span> =&gt; <span class="hljs-string">'_post'</span>,
]);
</code></pre>
<p>The <code>_post</code> view file could contain the following:</p>
<pre><code class="hljs php language-php"><span class="hljs-preprocessor">&lt;?php</span>
<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">helpers</span>\<span class="hljs-title">Html</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">helpers</span>\<span class="hljs-title">HtmlPurifier</span>;
<span class="hljs-preprocessor">?&gt;</span>
&lt;div <span class="hljs-class"><span class="hljs-keyword">class</span>="<span class="hljs-title">post</span>"&gt;
    &lt;<span class="hljs-title">h2</span>&gt;&lt;?= <span class="hljs-title">Html</span>::<span class="hljs-title">encode</span>($<span class="hljs-title">model</span>-&gt;<span class="hljs-title">title</span>) ?&gt;&lt;/<span class="hljs-title">h2</span>&gt;

    &lt;?= <span class="hljs-title">HtmlPurifier</span>::<span class="hljs-title">process</span>($<span class="hljs-title">model</span>-&gt;<span class="hljs-title">text</span>) ?&gt;    
&lt;/<span class="hljs-title">div</span>&gt;
</span></code></pre>
<p>In the view file above, the current data model is available as <code>$model</code>. Additionally the following variables are available:</p>
<ul>
<li><code>$key</code>: mixed, the key value associated with the data item.</li>
<li><code>$index</code>: integer, the zero-based index of the data item in the items array returned by the data provider.</li>
<li><code>$widget</code>: ListView, this widget instance.</li>
</ul>
<p>If you need to pass additional data to each view, you can use the <a href="./yii-widgets-listview.html#$viewParams-detail">$viewParams</a> property
to pass key value pairs like the following:</p>
<pre><code class="hljs php language-php"><span class="hljs-keyword">echo</span> ListView::widget([
    <span class="hljs-string">'dataProvider'</span> =&gt; <span class="hljs-variable">$dataProvider</span>,
    <span class="hljs-string">'itemView'</span> =&gt; <span class="hljs-string">'_post'</span>,
    <span class="hljs-string">'viewParams'</span> =&gt; [
        <span class="hljs-string">'fullView'</span> =&gt; <span class="hljs-keyword">true</span>,
        <span class="hljs-string">'context'</span> =&gt; <span class="hljs-string">'main-page'</span>,
        <span class="hljs-comment">// ...</span>
    ],
]);
</code></pre>
<p>These are then also available as variables in the view.</p>
<h2>GridView <a name="grid-view"></a> <span id="gridview"></span><a href="#gridview" class="hashlink">&para;</a></h2><p>Data grid or <a href="./yii-grid-gridview.html">GridView</a> is one of the most powerful Yii widgets. It is extremely useful if you need to quickly build the admin
section of the system. It takes data from a <a href="guide-output-data-providers.html">data provider</a> and renders each row using a set of <a href="./yii-grid-gridview.html#$columns-detail">columns</a>
presenting data in the form of a table.</p>
<p>Each row of the table represents the data of a single data item, and a column usually represents an attribute of
the item (some columns may correspond to complex expressions of attributes or static text).</p>
<p>The minimal code needed to use GridView is as follows:</p>
<pre><code class="hljs php language-php"><span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">grid</span>\<span class="hljs-title">GridView</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">data</span>\<span class="hljs-title">ActiveDataProvider</span>;

<span class="hljs-variable">$dataProvider</span> = <span class="hljs-keyword">new</span> ActiveDataProvider([
    <span class="hljs-string">'query'</span> =&gt; Post::find(),
    <span class="hljs-string">'pagination'</span> =&gt; [
        <span class="hljs-string">'pageSize'</span> =&gt; <span class="hljs-number">20</span>,
    ],
]);
<span class="hljs-keyword">echo</span> GridView::widget([
    <span class="hljs-string">'dataProvider'</span> =&gt; <span class="hljs-variable">$dataProvider</span>,
]);
</code></pre>
<p>The above code first creates a data provider and then uses GridView to display every attribute in every row taken from
the data provider. The displayed table is equipped with sorting and pagination functionality out of the box.</p>
<h3>Grid columns <span id="grid-columns"></span><a href="#grid-columns" class="hashlink">&para;</a></h3><p>The columns of the grid table are configured in terms of <a href="./yii-grid-column.html">yii\grid\Column</a> classes, which are
configured in the <a href="./yii-grid-gridview.html#$columns-detail">columns</a> property of GridView configuration.
Depending on column type and settings these are able to present data differently.
The default class is <a href="./yii-grid-datacolumn.html">yii\grid\DataColumn</a>, which represents a model attribute and can be sorted and filtered by.</p>
<pre><code class="hljs php language-php"><span class="hljs-keyword">echo</span> GridView::widget([
    <span class="hljs-string">'dataProvider'</span> =&gt; <span class="hljs-variable">$dataProvider</span>,
    <span class="hljs-string">'columns'</span> =&gt; [
        [<span class="hljs-string">'class'</span> =&gt; <span class="hljs-string">'yii\grid\SerialColumn'</span>],
        <span class="hljs-comment">// Simple columns defined by the data contained in $dataProvider.</span>
        <span class="hljs-comment">// Data from the model's column will be used.</span>
        <span class="hljs-string">'id'</span>,
        <span class="hljs-string">'username'</span>,
        <span class="hljs-comment">// More complex one.</span>
        [
            <span class="hljs-string">'class'</span> =&gt; <span class="hljs-string">'yii\grid\DataColumn'</span>, <span class="hljs-comment">// can be omitted, as it is the default</span>
            <span class="hljs-string">'value'</span> =&gt; <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-params">(<span class="hljs-variable">$data</span>)</span> </span>{
                <span class="hljs-keyword">return</span> <span class="hljs-variable">$data</span>-&gt;name; <span class="hljs-comment">// $data['name'] for array data, e.g. using SqlDataProvider.</span>
            },
        ],
    ],
]);
</code></pre>
<p>Note that if the <a href="./yii-grid-gridview.html#$columns-detail">columns</a> part of the configuration isn't specified,
Yii tries to show all possible columns of the data provider's model.</p>
<h3>Column classes <span id="column-classes"></span><a href="#column-classes" class="hashlink">&para;</a></h3><p>Grid columns could be customized by using different column classes:</p>
<pre><code class="hljs php language-php"><span class="hljs-keyword">echo</span> GridView::widget([
    <span class="hljs-string">'dataProvider'</span> =&gt; <span class="hljs-variable">$dataProvider</span>,
    <span class="hljs-string">'columns'</span> =&gt; [
        [
            <span class="hljs-string">'class'</span> =&gt; <span class="hljs-string">'yii\grid\SerialColumn'</span>, <span class="hljs-comment">// &lt;-- here</span>
            <span class="hljs-comment">// you may configure additional properties here</span>
        ],
</code></pre>
<p>In addition to column classes provided by Yii that we'll review below, you can create your own column classes.</p>
<p>Each column class extends from <a href="./yii-grid-column.html">yii\grid\Column</a> so that there are some common options you can set while configuring
grid columns.</p>
<ul>
<li><a href="./yii-grid-column.html#$header-detail">header</a> allows to set content for header row.</li>
<li><a href="./yii-grid-column.html#$footer-detail">footer</a> allows to set content for footer row.</li>
<li><a href="./yii-grid-column.html#$visible-detail">visible</a> defines if the column should be visible.</li>
<li><p><a href="./yii-grid-column.html#$content-detail">content</a> allows you to pass a valid PHP callback that will return data for a row. The format is the following:</p>
<pre><code class="hljs php language-php"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-params">(<span class="hljs-variable">$model</span>, <span class="hljs-variable">$key</span>, <span class="hljs-variable">$index</span>, <span class="hljs-variable">$column</span>)</span> </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">'a string'</span>;
}
</code></pre>
</li>
</ul>
<p>You may specify various container HTML options by passing arrays to:</p>
<ul>
<li><a href="./yii-grid-column.html#$headerOptions-detail">headerOptions</a></li>
<li><a href="./yii-grid-column.html#$footerOptions-detail">footerOptions</a></li>
<li><a href="./yii-grid-column.html#$filterOptions-detail">filterOptions</a></li>
<li><a href="./yii-grid-column.html#$contentOptions-detail">contentOptions</a></li>
</ul>
<h4>Data column  <span id="data-column"></span><a href="#data-column" class="hashlink">&para;</a></h4><p><a href="./yii-grid-datacolumn.html">Data column</a> is used for displaying and sorting data. It is the default column type so the specifying class could be omitted when
using it.</p>
<p>The main setting of the data column is its <a href="./yii-grid-datacolumn.html#$format-detail">format</a> property. Its values
correspond to methods in the <code>formatter</code> <a href="guide-structure-application-components.html">application component</a> that is <a href="./yii-i18n-formatter.html">Formatter</a> by default:</p>
<pre><code class="hljs php language-php"><span class="hljs-keyword">echo</span> GridView::widget([
    <span class="hljs-string">'columns'</span> =&gt; [
        [
            <span class="hljs-string">'attribute'</span> =&gt; <span class="hljs-string">'name'</span>,
            <span class="hljs-string">'format'</span> =&gt; <span class="hljs-string">'text'</span>
        ],
        [
            <span class="hljs-string">'attribute'</span> =&gt; <span class="hljs-string">'birthday'</span>,
            <span class="hljs-string">'format'</span> =&gt; [<span class="hljs-string">'date'</span>, <span class="hljs-string">'php:Y-m-d'</span>]
        ],
    ],
]);
</code></pre>
<p>In the above, <code>text</code> corresponds to <a href="./yii-i18n-formatter.html#asText()-detail">yii\i18n\Formatter::asText()</a>. The value of the column is passed as the first
argument. In the second column definition, <code>date</code> corresponds to <a href="./yii-i18n-formatter.html#asDate()-detail">yii\i18n\Formatter::asDate()</a>. The value of the
column is, again, passed as the first argument while 'php:Y-m-d' is used as the second argument value.</p>
<p>For a list of available formatters see the <a href="guide-output-formatting.html">section about Data Formatting</a>.</p>
<p>For configuring data columns there is also a shortcut format which is described in the
API documentation for <a href="./yii-grid-gridview.html#$columns-detail">columns</a>.</p>
<h4>Action column <span id="action-column"></span><a href="#action-column" class="hashlink">&para;</a></h4><p><a href="./yii-grid-actioncolumn.html">Action column</a> displays action buttons such as update or delete for each row.</p>
<pre><code class="hljs php language-php"><span class="hljs-keyword">echo</span> GridView::widget([
    <span class="hljs-string">'dataProvider'</span> =&gt; <span class="hljs-variable">$dataProvider</span>,
    <span class="hljs-string">'columns'</span> =&gt; [
        [
            <span class="hljs-string">'class'</span> =&gt; <span class="hljs-string">'yii\grid\ActionColumn'</span>,
            <span class="hljs-comment">// you may configure additional properties here</span>
        ],
</code></pre>
<p>Available properties you can configure are:</p>
<ul>
<li><a href="./yii-grid-actioncolumn.html#$controller-detail">controller</a> is the ID of the controller that should handle the actions. If not set, it will use the currently active
controller.</li>
<li><a href="./yii-grid-actioncolumn.html#$template-detail">template</a> defines the template used for composing each cell in the action column. Tokens enclosed within curly brackets are
treated as controller action IDs (also called <em>button names</em> in the context of action column). They will be replaced
by the corresponding button rendering callbacks specified in <a href="./yii-grid-actioncolumn.html#$buttons-detail">buttons</a>. For example, the token <code>{view}</code> will be
replaced by the result of the callback <code>buttons['view']</code>. If a callback cannot be found, the token will be replaced
with an empty string. The default tokens are <code>{view} {update} {delete}</code>.</li>
<li><p><a href="./yii-grid-actioncolumn.html#$buttons-detail">buttons</a> is an array of button rendering callbacks. The array keys are the button names (without curly brackets),
and the values are the corresponding button rendering callbacks. The callbacks should use the following signature:</p>
<pre><code class="hljs php language-php"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-params">(<span class="hljs-variable">$url</span>, <span class="hljs-variable">$model</span>, <span class="hljs-variable">$key</span>)</span> </span>{
    <span class="hljs-comment">// return the button HTML code</span>
}
</code></pre>
<p>In the code above, <code>$url</code> is the URL that the column creates for the button, <code>$model</code> is the model object being
rendered for the current row, and <code>$key</code> is the key of the model in the data provider array.</p>
</li>
<li><a href="./yii-grid-actioncolumn.html#$urlCreator-detail">urlCreator</a> is a callback that creates a button URL using the specified model information. The signature of
the callback should be the same as that of <a href="./yii-grid-actioncolumn.html#createUrl()-detail">yii\grid\ActionColumn::createUrl()</a>. If this property is not set,
button URLs will be created using <a href="./yii-grid-actioncolumn.html#createUrl()-detail">yii\grid\ActionColumn::createUrl()</a>.</li>
<li><p><a href="./yii-grid-actioncolumn.html#$visibleButtons-detail">visibleButtons</a> is an array of visibility conditions for each button.
The array keys are the button names (without curly brackets), and the values are the boolean true/false or the
anonymous function. When the button name is not specified in this array it will be shown by default.
The callbacks must use the following signature:</p>
<pre><code class="hljs php language-php"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-params">(<span class="hljs-variable">$model</span>, <span class="hljs-variable">$key</span>, <span class="hljs-variable">$index</span>)</span> </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-variable">$model</span>-&gt;status === <span class="hljs-string">'editable'</span>;
}
</code></pre>
<p>Or you can pass a boolean value:</p>
<pre><code class="hljs php language-php">[
    <span class="hljs-string">'update'</span> =&gt; \Yii::<span class="hljs-variable">$app</span>-&gt;user-&gt;can(<span class="hljs-string">'update'</span>)
]
</code></pre>
</li>
</ul>
<h4>Checkbox column <span id="checkbox-column"></span><a href="#checkbox-column" class="hashlink">&para;</a></h4><p><a href="./yii-grid-checkboxcolumn.html">Checkbox column</a> displays a column of checkboxes.</p>
<p>To add a CheckboxColumn to the GridView, add it to the <a href="./yii-grid-gridview.html#$columns-detail">columns</a> configuration as follows:</p>
<pre><code class="hljs php language-php"><span class="hljs-keyword">echo</span> GridView::widget([
    <span class="hljs-string">'dataProvider'</span> =&gt; <span class="hljs-variable">$dataProvider</span>,
    <span class="hljs-string">'columns'</span> =&gt; [
        <span class="hljs-comment">// ...</span>
        [
            <span class="hljs-string">'class'</span> =&gt; <span class="hljs-string">'yii\grid\CheckboxColumn'</span>,
            <span class="hljs-comment">// you may configure additional properties here</span>
        ],
    ],
</code></pre>
<p>Users may click on the checkboxes to select rows of the grid. The selected rows may be obtained by calling the following
JavaScript code:</p>
<pre><code class="hljs javascript language-javascript"><span class="hljs-keyword">var</span> keys = $(<span class="hljs-string">'#grid'</span>).yiiGridView(<span class="hljs-string">'getSelectedRows'</span>);
<span class="hljs-comment">// keys is an array consisting of the keys associated with the selected rows</span>
</code></pre>
<h4>Serial column <span id="serial-column"></span><a href="#serial-column" class="hashlink">&para;</a></h4><p><a href="./yii-grid-serialcolumn.html">Serial column</a> renders row numbers starting with <code>1</code> and going forward.</p>
<p>Usage is as simple as the following:</p>
<pre><code class="hljs php language-php"><span class="hljs-keyword">echo</span> GridView::widget([
    <span class="hljs-string">'dataProvider'</span> =&gt; <span class="hljs-variable">$dataProvider</span>,
    <span class="hljs-string">'columns'</span> =&gt; [
        [<span class="hljs-string">'class'</span> =&gt; <span class="hljs-string">'yii\grid\SerialColumn'</span>], <span class="hljs-comment">// &lt;-- here</span>
        <span class="hljs-comment">// ...</span>
</code></pre>
<h3>Sorting data <span id="sorting-data"></span><a href="#sorting-data" class="hashlink">&para;</a></h3><blockquote class="note"><p><strong>Note: </strong>This section is under development.</p>
<ul>
<li><a href="https://github.com/yiisoft/yii2/issues/1576">https://github.com/yiisoft/yii2/issues/1576</a></li>
</ul>
</blockquote>
<h3>Filtering data <span id="filtering-data"></span><a href="#filtering-data" class="hashlink">&para;</a></h3><p>For filtering data, the GridView needs a <a href="guide-structure-models.html">model</a> that represents the search criteria which is
usually taken from the filter fields in the GridView table.
A common practice when using <a href="guide-db-active-record.html">active records</a> is to create a search Model class
that provides needed functionality (it can be generated for you by <a href="guide-start-gii.html">Gii</a>). This class defines the validation
rules for the search and provides a <code>search()</code> method that will return the data provider with an
adjusted query that respects the search criteria.</p>
<p>To add the search capability for the <code>Post</code> model, we can create a <code>PostSearch</code> model like the following example:</p>
<pre><code class="hljs php language-php"><span class="hljs-preprocessor">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">app</span>\<span class="hljs-title">models</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">Yii</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">base</span>\<span class="hljs-title">Model</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">data</span>\<span class="hljs-title">ActiveDataProvider</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PostSearch</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Post</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">rules</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-comment">// only fields in rules() are searchable</span>
        <span class="hljs-keyword">return</span> [
            [[<span class="hljs-string">'id'</span>], <span class="hljs-string">'integer'</span>],
            [[<span class="hljs-string">'title'</span>, <span class="hljs-string">'creation_date'</span>], <span class="hljs-string">'safe'</span>],
        ];
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">scenarios</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-comment">// bypass scenarios() implementation in the parent class</span>
        <span class="hljs-keyword">return</span> Model::scenarios();
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">search</span><span class="hljs-params">(<span class="hljs-variable">$params</span>)</span>
    </span>{
        <span class="hljs-variable">$query</span> = Post::find();

        <span class="hljs-variable">$dataProvider</span> = <span class="hljs-keyword">new</span> ActiveDataProvider([
            <span class="hljs-string">'query'</span> =&gt; <span class="hljs-variable">$query</span>,
        ]);

        <span class="hljs-comment">// load the search form data and validate</span>
        <span class="hljs-keyword">if</span> (!(<span class="hljs-variable">$this</span>-&gt;load(<span class="hljs-variable">$params</span>) &amp;&amp; <span class="hljs-variable">$this</span>-&gt;validate())) {
            <span class="hljs-keyword">return</span> <span class="hljs-variable">$dataProvider</span>;
        }

        <span class="hljs-comment">// adjust the query by adding the filters</span>
        <span class="hljs-variable">$query</span>-&gt;andFilterWhere([<span class="hljs-string">'id'</span> =&gt; <span class="hljs-variable">$this</span>-&gt;id]);
        <span class="hljs-variable">$query</span>-&gt;andFilterWhere([<span class="hljs-string">'like'</span>, <span class="hljs-string">'title'</span>, <span class="hljs-variable">$this</span>-&gt;title])
              -&gt;andFilterWhere([<span class="hljs-string">'like'</span>, <span class="hljs-string">'creation_date'</span>, <span class="hljs-variable">$this</span>-&gt;creation_date]);

        <span class="hljs-keyword">return</span> <span class="hljs-variable">$dataProvider</span>;
    }
}
</code></pre>
<blockquote class="tip"><p><strong>Tip: </strong>See <a href="guide-db-query-builder.html">Query Builder</a> and especially <a href="guide-db-query-builder.html#filter-conditions">Filter Conditions</a>
to learn how to build filtering query.</p>
</blockquote>
<p>You can use this function in the controller to get the dataProvider for the GridView:</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$searchModel</span> = <span class="hljs-keyword">new</span> PostSearch();
<span class="hljs-variable">$dataProvider</span> = <span class="hljs-variable">$searchModel</span>-&gt;search(Yii::<span class="hljs-variable">$app</span>-&gt;request-&gt;get());

<span class="hljs-keyword">return</span> <span class="hljs-variable">$this</span>-&gt;render(<span class="hljs-string">'myview'</span>, [
    <span class="hljs-string">'dataProvider'</span> =&gt; <span class="hljs-variable">$dataProvider</span>,
    <span class="hljs-string">'searchModel'</span> =&gt; <span class="hljs-variable">$searchModel</span>,
]);
</code></pre>
<p>And in the view you then assign the <code>$dataProvider</code> and <code>$searchModel</code> to the GridView:</p>
<pre><code class="hljs php language-php"><span class="hljs-keyword">echo</span> GridView::widget([
    <span class="hljs-string">'dataProvider'</span> =&gt; <span class="hljs-variable">$dataProvider</span>,
    <span class="hljs-string">'filterModel'</span> =&gt; <span class="hljs-variable">$searchModel</span>,
    <span class="hljs-string">'columns'</span> =&gt; [
        <span class="hljs-comment">// ...</span>
    ],
]);
</code></pre>
<h3>Separate filter form <span id="separate-filter-form"></span><a href="#separate-filter-form" class="hashlink">&para;</a></h3><p>Most of the time using GridView header filters is enough, but in case you need a separate filter form,
you can easily add it as well. You can create partial view <code>_search.php</code> with the following contents:</p>
<pre><code class="hljs php language-php"><span class="hljs-preprocessor">&lt;?php</span>

<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">helpers</span>\<span class="hljs-title">Html</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">widgets</span>\<span class="hljs-title">ActiveForm</span>;

<span class="hljs-comment">/* <span class="hljs-doctag">@var</span> $this yii\web\View */</span>
<span class="hljs-comment">/* <span class="hljs-doctag">@var</span> $model app\models\PostSearch */</span>
<span class="hljs-comment">/* <span class="hljs-doctag">@var</span> $form yii\widgets\ActiveForm */</span>
<span class="hljs-preprocessor">?&gt;</span>

&lt;div <span class="hljs-class"><span class="hljs-keyword">class</span>="<span class="hljs-title">post</span>-<span class="hljs-title">search</span>"&gt;
    &lt;?<span class="hljs-title">php</span> $<span class="hljs-title">form</span> = <span class="hljs-title">ActiveForm</span>::<span class="hljs-title">begin</span>([
        '<span class="hljs-title">action</span>' =&gt; ['<span class="hljs-title">index</span>'],
        '<span class="hljs-title">method</span>' =&gt; '<span class="hljs-title">get</span>',
    ]); ?&gt;

    &lt;?= $<span class="hljs-title">form</span>-&gt;<span class="hljs-title">field</span>($<span class="hljs-title">model</span>, '<span class="hljs-title">title</span>') ?&gt;

    &lt;?= $<span class="hljs-title">form</span>-&gt;<span class="hljs-title">field</span>($<span class="hljs-title">model</span>, '<span class="hljs-title">creation_date</span>') ?&gt;

    &lt;<span class="hljs-title">div</span> <span class="hljs-title">class</span>="<span class="hljs-title">form</span>-<span class="hljs-title">group</span>"&gt;
        &lt;?= <span class="hljs-title">Html</span>::<span class="hljs-title">submitButton</span>('<span class="hljs-title">Search</span>', ['<span class="hljs-title">class</span>' =&gt; '<span class="hljs-title">btn</span> <span class="hljs-title">btn</span>-<span class="hljs-title">primary</span>']) ?&gt;
        &lt;?= <span class="hljs-title">Html</span>::<span class="hljs-title">submitButton</span>('<span class="hljs-title">Reset</span>', ['<span class="hljs-title">class</span>' =&gt; '<span class="hljs-title">btn</span> <span class="hljs-title">btn</span>-<span class="hljs-title">default</span>']) ?&gt;
    &lt;/<span class="hljs-title">div</span>&gt;

    &lt;?<span class="hljs-title">php</span> <span class="hljs-title">ActiveForm</span>::<span class="hljs-title">end</span>(); ?&gt;
&lt;/<span class="hljs-title">div</span>&gt;
</span></code></pre>
<p>and include it in <code>index.php</code> view like so:</p>
<pre><code class="hljs php language-php"><span class="hljs-preprocessor">&lt;?</span>= <span class="hljs-variable">$this</span>-&gt;render(<span class="hljs-string">'_search'</span>, [<span class="hljs-string">'model'</span> =&gt; <span class="hljs-variable">$searchModel</span>]) <span class="hljs-preprocessor">?&gt;</span>
</code></pre>
<blockquote class="note"><p><strong>Note: </strong>if you use Gii to generate CRUD code, the separate filter form (<code>_search.php</code>) is generated by default,
but is commented in <code>index.php</code> view. Uncomment it and it's ready to use!</p>
</blockquote>
<p>Separate filter form is useful when you need to filter by fields, that are not displayed in GridView
or for special filtering conditions, like date range. For filtering by date range we can add non DB attributes
<code>createdFrom</code> and <code>createdTo</code> to the search model:</p>
<pre><code class="hljs php language-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PostSearch</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Post</span>
</span>{
    <span class="hljs-comment">/**
     * <span class="hljs-doctag">@var</span> string
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-variable">$createdFrom</span>;

    <span class="hljs-comment">/**
     * <span class="hljs-doctag">@var</span> string
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-variable">$createdTo</span>;
}
</code></pre>
<p>Extend query conditions in the <code>search()</code> method like so:</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$query</span>-&gt;andFilterWhere([<span class="hljs-string">'&gt;='</span>, <span class="hljs-string">'creation_date'</span>, <span class="hljs-variable">$this</span>-&gt;createdFrom])
      -&gt;andFilterWhere([<span class="hljs-string">'&lt;='</span>, <span class="hljs-string">'creation_date'</span>, <span class="hljs-variable">$this</span>-&gt;createdTo]);
</code></pre>
<p>And add the representative fields to the filter form:</p>
<pre><code class="hljs php language-php"><span class="hljs-preprocessor">&lt;?</span>= <span class="hljs-variable">$form</span>-&gt;field(<span class="hljs-variable">$model</span>, <span class="hljs-string">'creationFrom'</span>) <span class="hljs-preprocessor">?&gt;</span>

<span class="hljs-preprocessor">&lt;?</span>= <span class="hljs-variable">$form</span>-&gt;field(<span class="hljs-variable">$model</span>, <span class="hljs-string">'creationTo'</span>) <span class="hljs-preprocessor">?&gt;</span>
</code></pre>
<h3>Working with model relations <span id="working-with-model-relations"></span><a href="#working-with-model-relations" class="hashlink">&para;</a></h3><p>When displaying active records in a GridView you might encounter the case where you display values of related
columns such as the post author's name instead of just his <code>id</code>.
You do this by defining the attribute name in <a href="./yii-grid-gridview.html#$columns-detail">yii\grid\GridView::$columns</a> as <code>author.name</code> when the <code>Post</code> model
has a relation named <code>author</code> and the author model has an attribute <code>name</code>.
The GridView will then display the name of the author but sorting and filtering are not enabled by default.
You have to adjust the <code>PostSearch</code> model that has been introduced in the last section to add this functionality.</p>
<p>To enable sorting on a related column you have to join the related table and add the sorting rule
to the Sort component of the data provider:</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$query</span> = Post::find();
<span class="hljs-variable">$dataProvider</span> = <span class="hljs-keyword">new</span> ActiveDataProvider([
    <span class="hljs-string">'query'</span> =&gt; <span class="hljs-variable">$query</span>,
]);

<span class="hljs-comment">// join with relation `author` that is a relation to the table `users`</span>
<span class="hljs-comment">// and set the table alias to be `author`</span>
<span class="hljs-variable">$query</span>-&gt;joinWith([<span class="hljs-string">'author'</span> =&gt; <span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">(<span class="hljs-variable">$query</span>)</span> </span>{ <span class="hljs-variable">$query</span>-&gt;from([<span class="hljs-string">'author'</span> =&gt; <span class="hljs-string">'users'</span>]); }]);
<span class="hljs-comment">// since version 2.0.7, the above line can be simplified to $query-&gt;joinWith('author AS author');</span>
<span class="hljs-comment">// enable sorting for the related column</span>
<span class="hljs-variable">$dataProvider</span>-&gt;sort-&gt;attributes[<span class="hljs-string">'author.name'</span>] = [
    <span class="hljs-string">'asc'</span> =&gt; [<span class="hljs-string">'author.name'</span> =&gt; SORT_ASC],
    <span class="hljs-string">'desc'</span> =&gt; [<span class="hljs-string">'author.name'</span> =&gt; SORT_DESC],
];

<span class="hljs-comment">// ...</span>
</code></pre>
<p>Filtering also needs the joinWith call as above. You also need to define the searchable column in attributes and rules like this:</p>
<pre><code class="hljs php language-php"><span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">attributes</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-comment">// add related fields to searchable attributes</span>
    <span class="hljs-keyword">return</span> array_merge(<span class="hljs-keyword">parent</span>::attributes(), [<span class="hljs-string">'author.name'</span>]);
}

<span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">rules</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-keyword">return</span> [
        [[<span class="hljs-string">'id'</span>], <span class="hljs-string">'integer'</span>],
        [[<span class="hljs-string">'title'</span>, <span class="hljs-string">'creation_date'</span>, <span class="hljs-string">'author.name'</span>], <span class="hljs-string">'safe'</span>],
    ];
}
</code></pre>
<p>In <code>search()</code> you then just add another filter condition with:</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$query</span>-&gt;andFilterWhere([<span class="hljs-string">'LIKE'</span>, <span class="hljs-string">'author.name'</span>, <span class="hljs-variable">$this</span>-&gt;getAttribute(<span class="hljs-string">'author.name'</span>)]);
</code></pre>
<blockquote class="info"><p><strong>Info: </strong>In the above we use the same string for the relation name and the table alias; however, when your alias and relation name
differ, you have to pay attention to where you use the alias and where you use the relation name.
A simple rule for this is to use the alias in every place that is used to build the database query and the
relation name in all other definitions such as <code>attributes()</code> and <code>rules()</code> etc.</p>
<p>For example, if you use the alias <code>au</code> for the author relation table, the joinWith statement looks like the following:</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$query</span>-&gt;joinWith([<span class="hljs-string">'author au'</span>]);
</code></pre>
<p>It is also possible to just call <code>$query-&gt;joinWith(['author']);</code> when the alias is defined in the relation definition.</p>
<p>The alias has to be used in the filter condition but the attribute name stays the same:</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$query</span>-&gt;andFilterWhere([<span class="hljs-string">'LIKE'</span>, <span class="hljs-string">'au.name'</span>, <span class="hljs-variable">$this</span>-&gt;getAttribute(<span class="hljs-string">'author.name'</span>)]);
</code></pre>
<p>The same is true for the sorting definition:</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$dataProvider</span>-&gt;sort-&gt;attributes[<span class="hljs-string">'author.name'</span>] = [
     <span class="hljs-string">'asc'</span> =&gt; [<span class="hljs-string">'au.name'</span> =&gt; SORT_ASC],
     <span class="hljs-string">'desc'</span> =&gt; [<span class="hljs-string">'au.name'</span> =&gt; SORT_DESC],
];
</code></pre>
<p>Also, when specifying the <a href="./yii-data-sort.html#$defaultOrder-detail">defaultOrder</a> for sorting, you need to use the relation name
instead of the alias:</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$dataProvider</span>-&gt;sort-&gt;defaultOrder = [<span class="hljs-string">'author.name'</span> =&gt; SORT_ASC];
</code></pre>
</blockquote>
<blockquote class="info"><p><strong>Info: </strong>For more information on <code>joinWith</code> and the queries performed in the background, check the
<a href="guide-db-active-record.html#joining-with-relations">active record docs on joining with relations</a>.</p>
</blockquote>
<h4>Using SQL views for filtering, sorting and displaying data <span id="using-sql-views-for-filtering-sorting-and-displaying-data"></span><a href="#using-sql-views-for-filtering-sorting-and-displaying-data" class="hashlink">&para;</a></h4><p>There is also another approach that can be faster and more useful - SQL views. For example, if we need to show the gridview
with users and their profiles, we can do so in this way:</p>
<pre><code class="hljs sql language-sql"><span class="hljs-operator"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">OR</span> <span class="hljs-keyword">REPLACE</span> <span class="hljs-keyword">VIEW</span> vw_user_info <span class="hljs-keyword">AS</span>
    <span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">user</span>.*, user_profile.lastname, user_profile.firstname
    <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">user</span>, user_profile
    <span class="hljs-keyword">WHERE</span> <span class="hljs-keyword">user</span>.<span class="hljs-keyword">id</span> = user_profile.user_id
</span></code></pre>
<p>Then you need to create the ActiveRecord that will be representing this view:</p>
<pre><code class="hljs php language-php">
<span class="hljs-keyword">namespace</span> <span class="hljs-title">app</span>\<span class="hljs-title">models</span>\<span class="hljs-title">views</span>\<span class="hljs-title">grid</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">db</span>\<span class="hljs-title">ActiveRecord</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserView</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">ActiveRecord</span>
</span>{

    <span class="hljs-comment">/**
     * <span class="hljs-doctag">@inheritdoc</span>
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">tableName</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">'vw_user_info'</span>;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">primaryKey</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-keyword">return</span> [<span class="hljs-string">'id'</span>];
    }

    <span class="hljs-comment">/**
     * <span class="hljs-doctag">@inheritdoc</span>
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">rules</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-keyword">return</span> [
            <span class="hljs-comment">// define here your rules</span>
        ];
    }

    <span class="hljs-comment">/**
     * <span class="hljs-doctag">@inheritdoc</span>
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">attributeLabels</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-keyword">return</span> [
            <span class="hljs-comment">// define here your attribute labels</span>
        ];
    }


}
</code></pre>
<p>After that you can use this UserView active record with search models, without additional specification of sorting and filtering attributes.
All attributes will be working out of the box. Note that this approach has several pros and cons:</p>
<ul>
<li>you don't need to specify different sorting and filtering conditions. Everything works out of the box;</li>
<li>it can be much faster because of the data size, count of sql queries performed (for each relation you will not need any additional query);</li>
<li>since this is just a simple mapping UI on the sql view it lacks some domain logic that is in your entities, so if you have some methods like <code>isActive</code>,
<code>isDeleted</code> or others that will influence the UI, you will need to duplicate them in this class too.</li>
</ul>
<h3>Multiple GridViews on one page <span id="multiple-gridviews-on-one-page"></span><a href="#multiple-gridviews-on-one-page" class="hashlink">&para;</a></h3><p>You can use more than one GridView on a single page but some additional configuration is needed so that
they do not interfere with each other.
When using multiple instances of GridView you have to configure different parameter names for
the generated sort and pagination links so that each GridView has its own individual sorting and pagination.
You do so by setting the <a href="./yii-data-sort.html#$sortParam-detail">sortParam</a> and <a href="./yii-data-pagination.html#$pageParam-detail">pageParam</a>
of the dataProvider's <a href="./yii-data-basedataprovider.html#$sort-detail">sort</a> and <a href="./yii-data-basedataprovider.html#$pagination-detail">pagination</a>
instances.</p>
<p>Assume we want to list the <code>Post</code> and <code>User</code> models for which we have already prepared two data providers
in <code>$userProvider</code> and <code>$postProvider</code>:</p>
<pre><code class="hljs php language-php"><span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">grid</span>\<span class="hljs-title">GridView</span>;

<span class="hljs-variable">$userProvider</span>-&gt;pagination-&gt;pageParam = <span class="hljs-string">'user-page'</span>;
<span class="hljs-variable">$userProvider</span>-&gt;sort-&gt;sortParam = <span class="hljs-string">'user-sort'</span>;

<span class="hljs-variable">$postProvider</span>-&gt;pagination-&gt;pageParam = <span class="hljs-string">'post-page'</span>;
<span class="hljs-variable">$postProvider</span>-&gt;sort-&gt;sortParam = <span class="hljs-string">'post-sort'</span>;

<span class="hljs-keyword">echo</span> <span class="hljs-string">'&lt;h1&gt;Users&lt;/h1&gt;'</span>;
<span class="hljs-keyword">echo</span> GridView::widget([
    <span class="hljs-string">'dataProvider'</span> =&gt; <span class="hljs-variable">$userProvider</span>,
]);

<span class="hljs-keyword">echo</span> <span class="hljs-string">'&lt;h1&gt;Posts&lt;/h1&gt;'</span>;
<span class="hljs-keyword">echo</span> GridView::widget([
    <span class="hljs-string">'dataProvider'</span> =&gt; <span class="hljs-variable">$postProvider</span>,
]);
</code></pre>
<h3>Using GridView with Pjax <span id="using-gridview-with-pjax"></span><a href="#using-gridview-with-pjax" class="hashlink">&para;</a></h3><p>The <a href="./yii-widgets-pjax.html">Pjax</a> widget allows you to update a certain section of a
page instead of reloading the entire page. You can use it to to update only the
<a href="./yii-grid-gridview.html">GridView</a> content when using filters.</p>
<pre><code class="hljs php language-php"><span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">widgets</span>\<span class="hljs-title">Pjax</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">grid</span>\<span class="hljs-title">GridView</span>;

Pjax::begin([
    <span class="hljs-comment">// PJax options</span>
]);
    Gridview::widget([
        <span class="hljs-comment">// GridView options</span>
    ]);
Pjax::end();
</code></pre>
<p>Pjax also works for the links inside the <a href="./yii-widgets-pjax.html">Pjax</a> widget and
for the links specified by <a href="./yii-widgets-pjax.html#$linkSelector-detail">Pjax::$linkSelector</a>.
But this might be a problem for the links of an <a href="./yii-grid-actioncolumn.html">ActionColumn</a>.
To prevent this, add the HTML attribute <code>data-pjax="0"</code> to the links when you edit
the <a href="./yii-grid-actioncolumn.html#$buttons-detail">ActionColumn::$buttons</a> property.</p>
<h4>GridView/ListView with Pjax in Gii <span id="gridviewlistview-with-pjax-in-gii"></span><a href="#gridviewlistview-with-pjax-in-gii" class="hashlink">&para;</a></h4><p>Since 2.0.5, the CRUD generator of <a href="guide-start-gii.html">Gii</a> has an option called
<code>$enablePjax</code> that can be used via either web interface or command line.</p>
<pre><code class="hljs php language-php">yii gii/crud --controllerClass=<span class="hljs-string">"backend\\controllers\PostController"</span> \
  --modelClass=<span class="hljs-string">"common\\models\\Post"</span> \
  --enablePjax=<span class="hljs-number">1</span>
</code></pre>
<p>Which generates a <a href="./yii-widgets-pjax.html">Pjax</a> widget wrapping the
<a href="./yii-grid-gridview.html">GridView</a> or <a href="./yii-widgets-listview.html">ListView</a> widgets.</p>
<h2>Further reading <span id="further-reading"></span><a href="#further-reading" class="hashlink">&para;</a></h2><ul>
<li><a href="http://www.sitepoint.com/rendering-data-in-yii-2-with-gridview-and-listview/">Rendering Data in Yii 2 with GridView and ListView</a> by Arno Slatius.</li>
</ul>
        <div class="toplink"><a href="#" class="h1" title="go to top"><span class="glyphicon glyphicon-arrow-up"></a></div>
    </div>
</div>


</div>

<footer class="footer">
        <p class="pull-right"><small>Page generated on Sat, 09 Jul 2016 12:16:30 +0000</small></p>
    Powered by <a href="http://www.yiiframework.com/" rel="external">Yii Framework</a></footer>

<script type="text/javascript">jQuery(document).ready(function () {
    var shiftWindow = function () { scrollBy(0, -50) };
    if (location.hash) setTimeout(shiftWindow, 1);
    window.addEventListener("hashchange", shiftWindow);
var element = document.createElement("script");
element.src = "./jssearch.index.js";
document.body.appendChild(element);

var searchBox = $('#searchbox');

// search when typing in search field
searchBox.on("keyup", function(event) {
    var query = $(this).val();

    if (query == '' || event.which == 27) {
        $('#search-resultbox').hide();
        return;
    } else if (event.which == 13) {
        var selectedLink = $('#search-resultbox a.selected');
        if (selectedLink.length != 0) {
            document.location = selectedLink.attr('href');
            return;
        }
    } else if (event.which == 38 || event.which == 40) {
        $('#search-resultbox').show();

        var selected = $('#search-resultbox a.selected');
        if (selected.length == 0) {
            $('#search-results').find('a').first().addClass('selected');
        } else {
            var next;
            if (event.which == 40) {
                next = selected.parent().next().find('a').first();
            } else {
                next = selected.parent().prev().find('a').first();
            }
            if (next.length != 0) {
                var resultbox = $('#search-results');
                var position = next.position();

//              TODO scrolling is buggy and jumps around
//                resultbox.scrollTop(Math.floor(position.top));
//                console.log(position.top);

                selected.removeClass('selected');
                next.addClass('selected');
            }
        }

        return;
    }
    $('#search-resultbox').show();
    $('#search-results').html('<li><span class="no-results">No results</span></li>');

    var result = jssearch.search(query);

    if (result.length > 0) {
        var i = 0;
        var resHtml = '';

        for (var key in result) {
            if (i++ > 20) {
                break;
            }
            resHtml = resHtml +
            '<li><a href="' + result[key].file.u.substr(3) +'"><span class="title">' + result[key].file.t + '</span>' +
            '<span class="description">' + result[key].file.d + '</span></a></li>';
        }
        $('#search-results').html(resHtml);
    }
});

// hide the search results on ESC
$(document).on("keyup", function(event) { if (event.which == 27) { $('#search-resultbox').hide(); } });
// hide search results on click to document
$(document).bind('click', function (e) { $('#search-resultbox').hide(); });
// except the following:
searchBox.bind('click', function(e) { e.stopPropagation(); });
$('#search-resultbox').bind('click', function(e) { e.stopPropagation(); });

});</script></body>
</html>
